package br.com.caelum.missao.controler;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.caelum.missao.dao.JdbcMissaoDao;
import br.com.caelum.missao.modelo.Missao;

@Controller
public class MissaoController {

	private final JdbcMissaoDao dao;
	@Autowired
	public MissaoController(JdbcMissaoDao dao){
		this.dao = dao;
	}
	@RequestMapping("missao")
	public String form() {
		return "missao/formulario";
	}

	@RequestMapping("adicionaMissao")
	public String adiciona(@Valid Missao missao, BindingResult result) {

		if (result.hasFieldErrors("descricao")) {
			return "redirect:formulario";
		}
		dao.adiciona(missao);
		return "redirect:formulario";
	}

	@RequestMapping("removeMissao")
	public void remove(Long id, HttpServletResponse response) {
		dao.remove(id);
		response.setStatus(200);
	}

	@RequestMapping("mostraMissao")
	public String mostra(Long id, Model model) {
		model.addAttribute("missao", dao.buscaPorId(id));
		return "missao/altera";
	}

	@RequestMapping("alteraMissao")
	public String altera(Missao missao) {
		dao.altera(missao);
		return "redirect:formulario";
	}

	@RequestMapping("finalizaMissao")
	public String finaliza(Long id, Model model) {
		dao.finaliza(id);
		model.addAttribute("missao", dao.buscaPorId(id));
		return "missao/finalizado";
	}

	@RequestMapping("formulario")
	public String lista(Model model) {
		List<Missao> missao = dao.lista();
		model.addAttribute("missoes", dao.lista());
		return "missao/formulario";
	}
}
